#include "../HttpResponse.h"
#include "../../../server/net/Buffer.h"
using namespace yhaida;

HttpResponse::HttpResponse(bool close)
    : _closeConnection(close),
      _stateCode(kUnknown)
{
}
void HttpResponse::setStatusCode(HttpStatusCode code)
{
    _stateCode = code;
}
void HttpResponse::setStatusQuery(const std::string &query)
{
    _query = query;
}

void HttpResponse::setCloseConnection(bool on)
{
    _closeConnection = on;
}
bool HttpResponse::closeConnection() const
{
    return _closeConnection;
}
void HttpResponse::setContentType(const std::string &contentType)
{
    addHeader("Content-Type", contentType);
}
void HttpResponse::addHeader(const std::string &key, const std::string &value)
{
    _headers[key] = value;
}
void HttpResponse::setBody(const std::string &body)
{
    _body = body;
}

void HttpResponse::appendToBuffer(Buffer *output) const
{
    char buffer[32];
    snprintf(buffer, sizeof(buffer), "HTTP/1.1 %d", _stateCode);
    output->append(buffer);
    output->append(_query);
    output->append("\r\n");

    if (_closeConnection)
    {
        output->append("Connection: close\r\n");
    }
    else
    {
        snprintf(buffer, sizeof(buffer), "Content-Length: %zd\r\n", _body.size());
        output->append(buffer);
        output->append("Connection: Keep-Alive\r\n");
    }

    for (const auto &header : _headers)
    {
        output->append(header.first);
        output->append(": ");
        output->append(header.second);
        output->append("\r\n");
    }

    output->append("\r\n");//空行
    output->append(_body);
}